package com.code.springboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.code.springboot.common.CustomException;
import com.code.springboot.dto.SetmealDto;
import com.code.springboot.entity.Dish;
import com.code.springboot.entity.DishFlavor;
import com.code.springboot.entity.Setmeal;
import com.code.springboot.entity.SetmealDish;
import com.code.springboot.mapper.SetmealMapper;
import com.code.springboot.service.SetmealDishService;
import com.code.springboot.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: springboot
 * @create: 2022-08-10 11:49
 **/
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;

    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        this.save(setmealDto);
        //添加菜品
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        //菜品内容
        setmealDishes.stream().map((item)->{
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        //保存
        setmealDishService.saveBatch(setmealDishes);
    }

    @Override
    @Transactional
    public void removeWithDish(List<Long> ids) {
        //select count(*) from setmeal where id in (1,2,3) and status = 1

        //查询套餐状态，确定是否能删除
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.in(Setmeal::getId,ids);
        queryWrapper.eq(Setmeal::getStatus,1);

        int count = this.count(queryWrapper);

        //若不能删除，则抛出异常
        if(count > 0){
            throw new CustomException("套餐正在售卖中，不能删除");
        }
        //若可以删除，则删除套餐表数据

        this.removeByIds(ids);
        //删除关联表数据
        LambdaQueryWrapper<SetmealDish> queryWrapper1 =new LambdaQueryWrapper<>();
        //delete from Setmeal_dish where Setmeal_id in (ids)
        queryWrapper1.in(SetmealDish::getSetmealId,ids);

        setmealDishService.remove(queryWrapper1);
    }

    @Override
    public void updateStatus(int status, List<Long> ids) {
        //通过id查菜品
        List<Setmeal> setmeals = this.listByIds(ids);
        //更新状态
        setmeals.forEach(setmeal -> setmeal.setStatus(status));

        this.updateBatchById(setmeals);
    }
}
